package com.bot.devbot.service.gitlab;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * gitlab接口封装
 * <a href="https://docs.gitlab.com/ee/api/rest/">gitlab api</a>
 * <a href="https://docs.gitlab.com/ee/api/commits.html?spm=5176.28103460.0.0.40f75d27znw3GL#get-the-diff-of-a-commit">gitlab api</a>
 * <a href="https://gitlab.cn/docs/jh/user/project/integrations/webhook_events.html">webhook_events</a>
 *
 * @author xialiguo
 * @version 1.0
 * @date 2025/1/21 15:36
 * @since 1.0
 */
@Slf4j
@Service
public class GitLabService {

    private String gitlabHost = "https://gitlab.annaji.com.cn";

    private String gitlabToken = "glpat-oy6YzVSyjUReNx4UjZ8u";


    // 获取用户有权限访问的所有项目
    public JSONArray getAllProjects() {
        String url = String.format("%s/api/v4/projects", gitlabHost);

        HttpResponse response = HttpRequest.get(url)
                .header("PRIVATE-TOKEN", gitlabToken)
                .form("membership", true) // 只获取当前用户有权限的项目
                .form("simple", true) // 简化返回数据
                .execute();

        if (response.getStatus() == 200) {
            return new JSONArray(response.body());
        }
        throw new RuntimeException("Failed to fetch projects from GitLab: " + response.body());
    }

    public JSONArray getAllProjectsV1() {
        String url = String.format("%s/api/v4/projects", gitlabHost);
        JSONArray allProjects = new JSONArray();
        int page = 1;
        int perPage = 100; // 每页最多可设置为 100
        boolean hasMore = true;

        while (hasMore) {
            HttpResponse response = HttpRequest.get(url)
                    .header("PRIVATE-TOKEN", gitlabToken)
                    .form("membership", true) // 只获取当前用户有权限的项目
                    .form("simple", true)    // 简化返回数据
                    .form("page", page)      // 当前页码
                    .form("per_page", perPage) // 每页返回的数量
                    .execute();

            if (response.getStatus() == 200) {
                JSONArray projects = new JSONArray(response.body());
                allProjects.addAll(projects);

                // 如果本页项目数量小于每页的最大数量，说明已经获取到最后一页
                if (projects.size() < perPage) {
                    hasMore = false;
                } else {
                    page++;
                }
            } else {
                throw new RuntimeException("Failed to fetch projects from GitLab: " + response.body());
            }
        }

        return allProjects;
    }

    // 获取项目的所有分支
    public JSONArray getBranches(String projectId) {
        String url = String.format("%s/api/v4/projects/%s/repository/branches", gitlabHost, projectId);

        HttpResponse response = HttpRequest.get(url)
                .header("PRIVATE-TOKEN", gitlabToken)
                .execute();

        if (response.getStatus() == 200) {
            return new JSONArray(response.body());
        }
        throw new RuntimeException("Failed to fetch branches from GitLab: " + response.body());
    }

    public JSONArray getBranchesV2(String projectId) {
        String url = String.format("%s/api/v4/projects/%s/repository/branches", gitlabHost, projectId);
        JSONArray allBranches = new JSONArray();
        int page = 1;
        int perPage = 100; // 每页最多可设置为 100
        boolean hasMore = true;

        while (hasMore) {
            HttpResponse response = HttpRequest.get(url)
                    .header("PRIVATE-TOKEN", gitlabToken)
                    .form("page", page)      // 当前页码
                    .form("per_page", perPage) // 每页返回的分支数量
                    .execute();

            if (response.getStatus() == 200) {
                JSONArray branches = new JSONArray(response.body());
                allBranches.addAll(branches);

                // 如果本页分支数量小于每页的最大数量，说明已经获取到最后一页
                if (branches.size() < perPage) {
                    hasMore = false;
                } else {
                    page++;
                }
            } else {
                throw new RuntimeException("Failed to fetch branches from GitLab: " + response.body());
            }
        }

        return allBranches;
    }

    public JSONArray getCommitsV2(String projectId, String branchName) {
        String url = String.format("%s/api/v4/projects/%s/repository/commits", gitlabHost, projectId);

        Map<String, Object> params = new HashMap<>();
        params.put("ref_name", branchName); // 指定分支
        params.put("per_page", 5);         // 只返回 20 条记录

        HttpResponse response = HttpRequest.get(url)
                .header("PRIVATE-TOKEN", gitlabToken)
                .form(params)
                .execute();

        if (response.getStatus() == 200) {
            return new JSONArray(response.body());
        }
        throw new RuntimeException("Failed to fetch commits from GitLab: " + response.body());
    }

    public JSONArray getAllCommits(String projectId, String branchName) {
        String url = String.format("%s/api/v4/projects/%s/repository/commits", gitlabHost, projectId);
        JSONArray allCommits = new JSONArray(); // 存储所有 commit
        int page = 1; // 初始页码
        int perPage = 100; // 每页返回的最大条数（GitLab 通常支持 100 条）

        while (true) {
            Map<String, Object> params = new HashMap<>();
            params.put("ref_name", branchName); // 指定分支
            params.put("per_page", perPage);    // 每页最大记录数
            params.put("page", page);          // 当前页码

            HttpResponse response = HttpRequest.get(url)
                    .header("PRIVATE-TOKEN", gitlabToken)
                    .form(params)
                    .execute();

            if (response.getStatus() == 200) {
                JSONArray commits = new JSONArray(response.body());
                if (commits.isEmpty()) {
                    break; // 如果当前页没有更多记录，结束循环
                }
                allCommits.addAll(commits); // 添加到结果列表
                page++; // 请求下一页
            } else {
                throw new RuntimeException("Failed to fetch commits from GitLab: " + response.body());
            }
        }

        return allCommits;
    }
}
